<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键词">
                <a-input v-model="queryParam.searchValue" allow-clear placeholder="请输入姓名/账号/手机号"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="所属学院">
                <a-select v-model="queryParam.collId" allow-clear placeholder="请选择"
                          :disabled="collSwitch">
                  <a-select-option v-for="(item,index) in collList" :key="index" :value="item.id">{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :rowKey="(record) => record.id"
        :rowSelection="options.rowSelection"
      >
        <template slot="operator">
          <a-button type="primary" icon="plus" @click="$refs.detail.open()">新增教师
          </a-button>
          <a-popconfirm title="确认批量删除？" @confirm="() => batchDelete()">
            <a-button type="danger" :disabled="selectedRowKeys.length < 1">
              <a-icon type="delete"/>
              批量删除
            </a-button>
          </a-popconfirm>
          <a-button @click="exportTmpl" v-if="hasRole('ca')">导出模板</a-button>
          <a-upload :customRequest="importTch" :multiple="false" :showUploadList="false" name="file">
            <a-button type="primary" v-if="hasRole('ca')">导入教师</a-button>
          </a-upload>
          <x-down ref="batchExport" style="display: none"/>
        </template>
        <span slot="sex" slot-scope="text">
            <span v-if="text===1">男</span>
            <span v-if="text===2">女</span>
            <span v-if="text===3">未知</span>
        </span>
        <span slot="status" slot-scope="text,record">
            <a-switch
              :loading="swtichLoading"
              checked-children="正常"
              un-checked-children="停用"
              :defaultChecked="text===0"
              @click="()=>editUserStatus(text,record)"/>
        </span>
        <span slot="action" slot-scope="text, record">
            <a @click="$refs.detail.open(record)">编辑</a>
            <a-divider type="vertical"/>
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多 <a-icon type="down"/>
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-popconfirm placement="topRight" title="确认重置密码？" @confirm="() => resetPwd(record)">
                    <a>重置密码</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
        </span>
        <span slot="ldrFlag" slot-scope="text, record">
          <a-tag color="red" v-if="record.ldrFlag!='1'">否</a-tag>
          <a-tag color="green" v-if="record.ldrFlag==='1'">是</a-tag>
        </span>
      </s-table>
    </a-card>
    <teacher-detail ref="detail" @ok="handleOk"/>
    <imp-error ref="impError" @ok="handleOk"/>
  </div>
</template>

<script>
  import store from '@/store'
  import { STable, XCard, XDown } from '@/components'
  import {
    exportUserTmpl,
    importUser,
    sysUserChangeStatus,
    sysUserDelete,
    sysUserExport,
    sysUserPageList,
    sysUserResetPwd
  } from '@/api/modular/system/userManage'
  import { Empty } from 'ant-design-vue'
  import TeacherDetail from './detail'
  import { sysCollegeList } from '@/api/modular/system/sysCollegeManage'
  import ImpError from './impError'

  export default {
    components: {
      XDown,
      XCard,
      STable,
      TeacherDetail,
      ImpError
    },
    data() {
      return {
        // 查询参数
        baseParam: {
          userType: 'tch'
        },
        // 查询参数
        queryParam: {
          searchValue: undefined,
          collId: undefined
        },
        // 表头
        columns: [
          {
            title: '所属学院',
            dataIndex: 'collName'
          },
          {
            title: '工号',
            dataIndex: 'userNum'
          },
          {
            title: '账号',
            dataIndex: 'account'
          },
          {
            title: '姓名',
            dataIndex: 'name'
          },
          {
            title: '性别',
            dataIndex: 'sex',
            scopedSlots: { customRender: 'sex' }
          },
          {
            title: '手机',
            dataIndex: 'phone'
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '院系管理员',
            dataIndex: 'ldrFlag',
            scopedSlots: { customRender: 'ldrFlag' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return sysUserPageList(Object.assign(parameter, { ...this.queryParam, ...this.baseParam })).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        options: {
          alert: {
            show: true, clear: () => {
              this.selectedRowKeys = []
            }
          },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        },
        swtichLoading: false,
        collList: [],
        collSwitch: store.getters.admintype != 1
      }
    },
    created() {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    },
    mounted() {
      this.getCollList()
      this.queryParam.collId = store.getters.admintype != 1 ? store.getters.userInfo.collId : undefined
    },
    methods: {
      resetSearch() {
        this.queryParam.searchValue = undefined
        if (store.getters.admintype === 1) {
          this.queryParam.collId = undefined
        }
      },
      getCollList() {
        sysCollegeList().then((res) => {
          if (res.success) {
            this.collList = res.data
          }
        })
      },
      /**
       * 修改用户状态
       */
      editUserStatus(code, record) {
        // eslint-disable-next-line no-unused-vars
        let status = 0
        let action = ''
        // eslint-disable-next-line eqeqeq
        if (code == 0) {
          status = 1
          action = '停用'
          // eslint-disable-next-line eqeqeq
        } else if (code == 1) {
          status = 0
          action = '启用'
        }
        this.swtichLoading = true
        sysUserChangeStatus({ id: record.id, status: status }).then(res => {
          if (res.success) {
            this.$message.success(action + '操作成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error(action + '操作失败：' + res.message)
          }
        }).finally(() => {
          this.swtichLoading = false
          this.$refs.table.refresh()
        })
      },
      /**
       * 重置密码
       */
      resetPwd(record) {
        sysUserResetPwd({ id: record.id }).then(res => {
          if (res.success) {
            this.$message.success('重置成功')
            // this.$refs.table.refresh()
          } else {
            this.$message.error('重置失败：' + res.message)
          }
        }).finally(() => {
          this.swtichLoading = false
          this.$refs.table.refresh()
        })
      },
      /**
       * 单个删除
       */
      singleDelete(record) {
        const param = [{ 'id': record.id }]
        this.sysUserDelete(param)
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const paramIds = this.selectedRowKeys.map((d) => {
          return { 'id': d }
        })
        this.sysUserDelete(paramIds)
      },
      /**
       * 删除用户
       */
      sysUserDelete(param) {
        sysUserDelete(param).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      /**
       * 批量导出
       */
      batchExport() {
        sysUserExport().then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      exportTmpl() {
        exportUserTmpl().then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      importTch(data) {
        const file = data.file
        const fileSize = file.size
        const fileType = file.name.substr(file.name.lastIndexOf('.'))
        console.log('fileType=', fileType)
        if (fileType !== '.xls' && fileType !== '.xlsx') {
          this.$message.error('请上传Excel文件')
          return
        }
        if (fileSize / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50M')
          return
        }
        const formData = new FormData()
        formData.append('type', 1)
        formData.append('file', file)
        this.$refs.table.localLoading = true
        importUser(formData).then((res) => {
          if (res.success) {
            this.$message.success('导入成功:' + res.data)
            this.$refs.table.refresh()
          } else {
            this.$message.error('导入失败：' + res.message)
            if (res.data) {
              this.$refs.impError.open(res.data)
            }
          }
        }).finally(() => {
          this.$refs.table.localLoading = false
        })
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>